package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper mapper;

    public List<Role> selectAll() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int count = mapper.query4Count(qo);
        if (count > 0) {
            return new PageResult(count, mapper.query4List(qo));
        }
        return new PageResult(count, Collections.EMPTY_LIST);
    }

    public void updateByPrimaryKey(Role record) {
        mapper.updateByPrimaryKey(record);
        mapper.deletePermissionRelation(record.getId());
        mapper.deleteMenuRelation(record.getId());
        //处理中间表
        List<Permission> permissions = record.getPermissions();
        for (Permission permission : permissions) {
            mapper.insertPermissionRelation(record.getId(),permission.getId());
        }
        List<Menu> menus = record.getMenus();
        for (Menu menu : menus) {
            mapper.insertMenuRelation(record.getId(),menu.getId());
        }
    }

    public void insert(Role record) {
        mapper.insert(record);
        //处理中间表
        List<Permission> permissions = record.getPermissions();
        for (Permission permission : permissions) {
            mapper.insertPermissionRelation(record.getId(),permission.getId());
        }
        List<Menu> menus = record.getMenus();
        for (Menu menu : menus) {
            mapper.insertMenuRelation(record.getId(),menu.getId());
        }
    }

    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    public List<Permission> selectPermissions(Long roleId) {
        return mapper.selectPermissions(roleId);
    }

    public List<Long> getMenuIdByRoleId(Long roleId) {
        return mapper.getMenuIdByRoleId(roleId);
    }

    public List<String> selectRoleByEmployeeId(Long id) {
        return mapper.selectRoleByEmployeeId(id);
    }

}
